<script lang="ts" setup>
import type { SystemInfo } from '#/api/core/user';

import { computed, onMounted, ref } from 'vue';

import { useAccessStore, useUserStore } from '@vben/stores';

import { ElCard, ElCol, ElLoading, ElMessage, ElRow } from 'element-plus';

import { callSystemLoginApi, getUserSystemListApi } from '#/api/core/user';

// 系统列表数据
const systems = ref<SystemInfo[]>([]);
// 加载状态
const loading = ref(false);

const accessStore = useAccessStore();
const userStore = useUserStore();

// 获取时间问候语
const greeting = computed(() => {
  const hour = new Date().getHours();
  const userName =
    userStore.userInfo?.realName || userStore.userInfo?.username || '用户';

  if (hour >= 6 && hour < 12) {
    return `上午好，${userName}`;
  } else if (hour >= 12 && hour < 18) {
    return `下午好，${userName}`;
  } else if (hour >= 18 && hour < 22) {
    return `晚上好，${userName}`;
  } else {
    return `夜深了，${userName}`;
  }
});

// 获取系统列表
const fetchSystemList = async () => {
  loading.value = true;
  try {
    const data = await getUserSystemListApi();
    systems.value = data;
  } catch (error) {
    ElMessage.error('获取系统列表失败');
    console.error('Error fetching system list:', error);
  } finally {
    loading.value = false;
  }
};

// 处理卡片点击事件
const handleCardClick = async (system: SystemInfo) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在调用登录回调接口...',
    background: 'rgba(0, 0, 0, 0.7)',
  });

  try {
    // 调用登录回调接口，传递系统ID
    await callSystemLoginApi(system.loginCallbackUrl, system.id);

    ElMessage.success('登录回调成功，正在跳转...');

    // 获取当前的 token
    const token = accessStore.accessToken;

    // 构建目标 URL，携带 token
    const targetUrl = `${system.url}?token=${encodeURIComponent(token || '')}`;

    // 在新窗口中打开
    window.open(targetUrl, '_blank');
  } catch (error) {
    ElMessage.error('登录回调失败');
    console.error('Error calling login callback:', error);
  } finally {
    loadingInstance.close();
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchSystemList();
});
</script>

<template>
  <div class="p-5">
    <div class="mb-4">
      <h2 class="text-2xl font-semibold">{{ greeting }}</h2>
    </div>

    <div v-if="loading" class="py-8 text-center">
      <p class="text-gray-500">加载中...</p>
    </div>

    <div v-else-if="systems.length === 0" class="py-8 text-center">
      <p class="text-gray-500">暂无可用系统</p>
    </div>

    <ElRow v-else :gutter="20" class="system-list">
      <ElCol
        v-for="system in systems"
        :key="system.id"
        :span="6"
        :lg="6"
        :md="8"
        :sm="12"
        :xs="24"
        class="mb-4"
      >
        <ElCard
          class="system-card cursor-pointer"
          :body-style="{ padding: '16px' }"
          @click="handleCardClick(system)"
        >
          <div class="flex flex-col">
            <!-- 上方图片 -->
            <div class="mb-3">
              <img
                :src="system.image"
                :alt="system.systemName"
                class="h-16 w-16 rounded-lg object-cover"
                @error="
                  ($event.target as HTMLImageElement).src =
                    'https://via.placeholder.com/64x64?text=No+Image'
                "
              />
            </div>

            <!-- 下方内容 -->
            <div class="text-left">
              <div class="mb-2">
                <h3
                  class="truncate text-lg font-bold"
                  :title="system.systemName"
                >
                  {{ system.systemName }}
                </h3>
              </div>

              <div class="mb-3 text-sm text-gray-600">
                <p class="line-clamp-2" :title="system.desc">
                  {{ system.desc || '暂无描述' }}
                </p>
              </div>

              <div>
                <span class="text-sm text-blue-500"> 跳转 >> </span>
              </div>
            </div>
          </div>
        </ElCard>
      </ElCol>
    </ElRow>
  </div>
</template>

<style scoped>
.system-card {
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
  transform: scale(1);
}

.system-card:hover {
  transform: scale(1.08) translateY(-4px);
  border-color: #3b82f6;
  box-shadow:
    0 10px 25px -5px rgba(0, 0, 0, 0.1),
    0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.system-list {
  min-height: 200px;
}
</style>
